package com.focus.xyz.union.pages.frontend.tables;

import com.focus.xyz.core.common.keyword.Action;
import com.focus.xyz.core.pages.BaseTable;
import com.focus.xyz.core.utils.Constants;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import java.util.List;

/**
 * Created by chenmeng on 2016/5/23.
 */
public class OrderTable extends BaseTable {
    private WebDriver driver;

    @FindBy(className = "order-mana-table")
    private WebElement orderTable;
    @FindBy(xpath = "//span[@class='ui-money']")
    private WebElement totalFee;
    @FindBy(xpath = "//a[text()='确认订单']")
    private List<WebElement> confirmBtn;

    /*客服代客下单后，客户在订单列表中确认订单后直接支付*/
    @FindBy(xpath = "//a[text()='立即支付']")
    private WebElement payBtn;
    @FindBy(id = "payPwd")
    private WebElement payPwd;
    @FindBy(id = "agreeToPay")
    private WebElement agreeToPay;

    public OrderTable(WebDriver driver,Action action) {
        super(action);
        this.driver = driver;
        PageFactory.initElements(driver,this);
    }

    @Override
    protected By getLinkLocator() throws Exception {
        return By.xpath("td[5]/a");
    }

    @Override
    protected By getLocator(int index) throws Exception {
        return By.xpath("td[" + index + "]/div");
    }

    public void linkOrderInfo(String key) throws Exception{
        selectRowAndClickLink(orderTable,key,"查看频道");

    }

    public String getAppStatus(String key) throws Exception{
        return getCellText(orderTable,key,3).trim();
    }

    public String getAppFee() throws Exception{
        return totalFee.getText().substring(1).trim();
    }

    public String getOrderStatus(String key) throws Exception{
        return getCellText(orderTable,key,5).trim();
    }

    @Override
    public String getCellText(WebElement table, String key, int index) throws Exception{
        String target = null;
        List<WebElement> rows = table.findElements(By.tagName(Constants.TAG_TR));
        OUT:for(WebElement row:rows){
            List<WebElement> cols = row.findElements(By.tagName(Constants.TAG_TD));
            for(WebElement col:cols){
                if(key.equals(col.getText().split("\n")[0])){
                    if(null != getLocator(index)){
                        target = row.findElement(getLocator(index)).getText();
                        break OUT;
                    }
                }
            }
        }
        return target;
    }

    public void confirmOrder() throws Exception{
        action.click(confirmBtn.get(0));
        action.switchToWindowByUrl("http://union.xyz.cn/ordertrans/normalApp",true);
    }

    public void pay(String pass) throws Exception{
        action.pause(2000l);
        action.click(payBtn);
        action.inputText(payPwd,pass);
        action.click(agreeToPay);
    }
}
